/**
 * Notes: 样品管理模块服务
 * Date: 2024-03-11
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 */

const BaseProjectService = require('./base_project_service.js');
const dataUtil = require('../../../framework/helpers/data_util.js');
const timeUtil = require('../../../framework/helpers/time_util.js');
const SampleModel = require('../config/models_config').sample_model;
const ProjectModel = require('../config/models_config').project_model;
const UserModel = require('../config/models_config').user_model;
const util = require('../../../framework/helpers/util.js');
const cloudUtil = require('../../../framework/cloud/cloud_util.js');

class SampleService extends BaseProjectService {

    /**
     * 获取样品列表
     * @param {Object} param - 查询参数
     */
    async getSampleList(param) {
        let where = {};

        if (param.search) {
            let search = dataUtil.getSearch(param.search);
            where.or = [
                { SAMPLE_CODE: { $regex: search, $options: 'i' } },
                { SAMPLE_NAME: { $regex: search, $options: 'i' } },
                { SAMPLE_VERSION: { $regex: search, $options: 'i' } },
                { SAMPLE_CUSTOMER: { $regex: search, $options: 'i' } }
            ];
        }

        if (param.status) where.SAMPLE_STATUS = Number(param.status);

        let orderBy = {};
        if (param.sortType && param.sortVal) {
            orderBy = {
                [param.sortType]: param.sortVal
            }
        } else {
            orderBy = {
                'createTime': 'desc'
            }
        }

        let fields = '*';
        let page = param.page;
        let size = param.size;
        let isTotal = true;
        let oldTotal = 0;
        
        let sampleModel = new SampleModel();
        let list = await sampleModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);

        // 取出关联的项目信息
        let projectIds = [];
        for (let k = 0; k < list.list.length; k++) {
            if (list.list[k].SAMPLE_PROJECT_ID) 
                projectIds.push(list.list[k].SAMPLE_PROJECT_ID);
        }

        // 获取关联项目数据
        let projects = [];
        if (projectIds.length > 0) {
            let projectModel = new ProjectModel();
            projects = await projectModel.getListByIds(projectIds, 'PROJECT_NAME');
        }

        // 补充项目信息
        for (let k = 0; k < list.list.length; k++) {
            let item = list.list[k];
            
            // 处理项目信息
            if (item.SAMPLE_PROJECT_ID) {
                let project = projects.find(p => p._id === item.SAMPLE_PROJECT_ID);
                item.projectName = project ? project.PROJECT_NAME : '未知项目';
            } else {
                item.projectName = '';
            }

            // 处理状态文字
            item.statusDesc = this._getStatusDesc(item.SAMPLE_STATUS);
        }

        return list;
    }

    /**
     * 获取样品详情
     * @param {String} id - 样品ID
     */
    async getSampleDetail(id) {
        let fields = '*';
        let sampleModel = new SampleModel();
        let sample = await sampleModel.getOne({ _id: id }, fields);
        if (!sample) return null;

        // 关联项目信息
        if (sample.SAMPLE_PROJECT_ID) {
            let projectModel = new ProjectModel();
            let project = await projectModel.getOne({ _id: sample.SAMPLE_PROJECT_ID }, 'PROJECT_NAME');
            sample.projectName = project ? project.PROJECT_NAME : '未知项目';
        } else {
            sample.projectName = '';
        }

        // 关联工程师信息
        if (sample.SAMPLE_MAKE_USER_ID) {
            let userModel = new UserModel();
            let user = await userModel.getOne({ USER_MINI_OPENID: sample.SAMPLE_MAKE_USER_ID }, 'USER_NAME');
            sample.engineerName = user ? user.USER_NAME : '未知';
        } else {
            sample.engineerName = '';
        }

        // 处理状态文字
        sample.statusDesc = this._getStatusDesc(sample.SAMPLE_STATUS);

        return sample;
    }

    /**
     * 添加样品
     * @param {Object} data - 样品数据
     */
    async insertSample(data) {
        let sampleModel = new SampleModel();

        // 生成样品ID
        data.SAMPLE_ID = dataUtil.genRandomLetterNumber(15);

        // 检查权限
        if (!await this.checkSampleAddPermission(this._userId))
            this.appError('您没有添加样品的权限，请联系测试组');

        // 创建样品
        let id = await sampleModel.insert(data);

        return { id };
    }

    /**
     * 编辑样品
     * @param {Object} data - 样品数据
     */
    async editSample(data) {
        let sampleModel = new SampleModel();
        let id = data.id;
        delete data.id;

        // 检查是否存在
        let sample = await sampleModel.getOne({ _id: id });
        if (!sample) this.appError('样品不存在');

        // 检查权限
        if (!await this.checkSampleAddPermission(this._userId))
            this.appError('您没有编辑样品的权限，请联系测试组');

        // 更新样品
        await sampleModel.edit({ _id: id }, data);

        return { id };
    }

    /**
     * 删除样品
     * @param {String} id - 样品ID
     */
    async delSample(id) {
        let sampleModel = new SampleModel();

        // 检查是否存在
        let sample = await sampleModel.getOne({ _id: id });
        if (!sample) this.appError('样品不存在');

        // 检查权限
        if (!await this.checkSampleAddPermission(this._userId))
            this.appError('您没有删除样品的权限，请联系测试组');

        // 删除图片
        if (sample.SAMPLE_ATTACHMENTS && sample.SAMPLE_ATTACHMENTS.length > 0) {
            for (let i = 0; i < sample.SAMPLE_ATTACHMENTS.length; i++) {
                let url = sample.SAMPLE_ATTACHMENTS[i];
                await cloudUtil.deleteFiles(url);
            }
        }

        // 删除样品
        await sampleModel.del({ _id: id });
    }

    /**
     * 获取样品状态选项
     */
    async getSampleStatusOptions() {
        return [
            { label: '调试中', value: 1 },
            { label: '试产中', value: 2 },
            { label: '大货中', value: 3 }
        ];
    }

    /**
     * 获取项目选项列表
     */
    async getProjectOptions() {
        let projectModel = new ProjectModel();
        let where = {};
        let fields = '_id,PROJECT_NAME';
        let orderBy = { 'PROJECT_NAME': 'asc' };
        let projects = await projectModel.getAll(where, fields, orderBy);
        
        let options = [];
        for (let k = 0; k < projects.length; k++) {
            options.push({
                label: projects[k].PROJECT_NAME,
                value: projects[k]._id
            });
        }
        
        return options;
    }

    /**
     * 检查用户是否有样品管理权限
     * @param {String} userId - 用户ID
     */
    async checkSampleAddPermission(userId) {
        // 调试模式：设置为true时暂时放开权限检查
        const DEBUG_MODE = true;
        
        if (DEBUG_MODE) return true;
        
        if (!userId) return false;

        // 获取当前用户信息
        let userModel = new UserModel();
        let user = await userModel.getOne({ USER_MINI_OPENID: userId });
        if (!user) return false;

        // 只有测试组可以管理样品
        return user.USER_DEPT === '测试组';
    }

    /**
     * 获取状态描述
     * @param {Number} status - 状态码
     */
    _getStatusDesc(status) {
        switch (status) {
            case 1: return '调试中';
            case 2: return '试产中';
            case 3: return '大货中';
            default: return '未知';
        }
    }
}

module.exports = SampleService; 